import React, { useEffect, useState } from 'react';
import axios from 'axios';
import { Table, Space, Input, Button } from 'antd';
import moment from 'moment';

const User2 = () => {
  const [dataa, setData] = useState([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(0);
  const [searchTerm, setSearchTerm] = useState('');
  const [filteredData, setFilteredData] = useState([]);
  const [delectid, setDelectid] = useState('')
  useEffect(() => {
    fetchData();
  }, []);
  const delect = async (record) => {
    setDelectid()
    // try {
    //   const response = await axios.delete(`https://r5ctn9z9.lc-cn-n1-shared.com/1.1/classes/bscs/${record.key}`, {
    //     headers: {
    //         " X-LC-Id": "r5CTN9z96pCW8mI8fx9YxOmw-gzGzoHsz",
    //         "X-LC-Key": "8gSsl4Sz0ILMiQeMNMA8xQqg",
    //         "Content-Type": ""
    //     }

    //   }).then((res) => {
    //   // console.log(delectid)
    //   setData(dataa.filter(item => item.key !== record.key))






    axios.get(`https://r5ctn9z9.lc-cn-n1-shared.com/1.1/classes/image?where={"image_id":"${record.key}"}`, {
      headers: {
        " X-LC-Id": "r5CTN9z96pCW8mI8fx9YxOmw-gzGzoHsz",
        "X-LC-Key": "8gSsl4Sz0ILMiQeMNMA8xQqg",
        "Content-Type": "application/json"
      }
    }).then((res) => {
      console.log(res)
      if (res.data.results[0].length !== 0) {
        axios.delete(`https://r5ctn9z9.lc-cn-n1-shared.com/1.1/classes/image/${res.data.results[0].objectId}`, {
          headers: {
            " X-LC-Id": "r5CTN9z96pCW8mI8fx9YxOmw-gzGzoHsz",
            "X-LC-Key": "8gSsl4Sz0ILMiQeMNMA8xQqg",
            "Content-Type": "application/json"
          }
        }).then((res) => {
          // console.log(res)
          console.log('附属图片删除成功')
        }).catch((error) => {
          console.log(error)
        })
      }
    }).catch((error) => {
      console.log(error)
    })







    axios.delete(`https://r5ctn9z9.lc-cn-n1-shared.com/1.1/classes/bscs/${record.key}`, {
      headers: {
        " X-LC-Id": "r5CTN9z96pCW8mI8fx9YxOmw-gzGzoHsz",
        "X-LC-Key": "8gSsl4Sz0ILMiQeMNMA8xQqg",
        "Content-Type": "application/json"
      }
    }).then((res) => {
      console.log('删除成功')
      setData(dataa.filter(item => item.key !== record.key))

      axios.get(`https://r5ctn9z9.lc-cn-n1-shared.com/1.1/classes/food?where={"Commodity_id":"${record.key}"}`, {
        headers: {
          " X-LC-Id": "r5CTN9z96pCW8mI8fx9YxOmw-gzGzoHsz",
          "X-LC-Key": "8gSsl4Sz0ILMiQeMNMA8xQqg",
          "Content-Type": ""
        }
      }).then((e) => {
        console.log(e)

        if (e.data.results.length !== 0) {
          for (let i = 0; i < e.data.results.length; i++) {
            axios.delete(`https://r5ctn9z9.lc-cn-n1-shared.com/1.1/classes/food/${e.data.results[i].objectId}`, {
              headers: {
                " X-LC-Id": "r5CTN9z96pCW8mI8fx9YxOmw-gzGzoHsz",
                "X-LC-Key": "8gSsl4Sz0ILMiQeMNMA8xQqg",
                "Content-Type": ""
              }
            }).then(() => {
              console.log("删除成功")

              // navigate('/dianpu')
            }).catch((error) => {
              console.log('出错', error)
            })
          }
        }
        // navigate('/dianpu')


      })




    }).catch((error) => {
      console.log('删除失败', error)
    })









    //   });


    // } catch (error) {
    //   console.log(error);
    // }
  }

  const fetchData = async () => {
    try {
      const response = await axios.get(`https://r5ctn9z9.lc-cn-n1-shared.com/1.1/classes/bscs`, {
        headers: {
          " X-LC-Id": "r5CTN9z96pCW8mI8fx9YxOmw-gzGzoHsz",
          "X-LC-Key": "8gSsl4Sz0ILMiQeMNMA8xQqg",
          "Content-Type": ""
        }

      }).then((res) => {
        console.log(res)
        const formattedData = res.data.results.map((item) => ({
          //  formattedData = moment(item.createdAt).format('YYYY-MM-DD');
          ...item,
          key: item.objectId, // 将objectId作为key值


          createdAt: moment(item.createdAt).format('YYYY-MM-DD-hh:mm:ss'),
          updatedAt: moment(item.updatedAt).format('YYYY-MM-DD-HH:mm:ss'),



        }));

        setData(formattedData);



        setTotalPages(Math.ceil(res.data.count / 10));
      });


    } catch (error) {
      console.log(error);
    }
  };
  // 分页
  const handlePageChange = (page) => {
    setCurrentPage(page);
  };

  const columns = [
    {
      title: '商品ID',
      dataIndex: 'objectId',
      key: 'objectId',
      // setDelectid(objectId)
    },
    {
      title: '商品名称',
      dataIndex: 'xiangqing',
      key: 'xiangqing',

    },
    {
      title: '商品图片',
      dataIndex: 'image',
      key: 'image',

    },
    {
      title: '所属商家',
      dataIndex: 'people_id',
      key: 'people_id',

    },
    {
      title: '商品价格',
      dataIndex: 'price',
      key: 'price'
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt'
    },
    {
      title: '更新时间',
      dataIndex: 'updatedAt',
      key: 'updatedAt'
    },
    {
      title: 'Action',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          {/* <a>Invite</a> */}
          <a onClick={() => delect(record)}>Delete</a>
        </Space>
      ),
    },

    // Add more columns as needed
  ];

  //   const handleChange = (event) => {
  //     setSearchTerm(event.target.value);
  //   };

  const handleSearch = () => {
    console.log("搜索内容：", searchTerm, dataa);
    const filtered = dataa.filter(item => item.xiangqing.includes(searchTerm));
    // 在这里可以执行你的查询操作，展示结果等
    setFilteredData(filtered)
  };


  const datanew = () => {
    const pageSize = 10;
    const data = filteredData.length > 0 ? filteredData : dataa;
    const startIndex = (currentPage - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    return data.slice(startIndex, endIndex);
  }
  console.log(datanew())
  // console.log(delect())


  //   const delectsp = (event) => {
  //     event.preventDefault();

  //     axios.get(`https://r5ctn9z9.lc-cn-n1-shared.com/1.1/classes/image?where={"image_id":"${objectId}"}`, {
  //         headers: {
  //             " X-LC-Id": "r5CTN9z96pCW8mI8fx9YxOmw-gzGzoHsz",
  //             "X-LC-Key": "8gSsl4Sz0ILMiQeMNMA8xQqg",
  //             "Content-Type": "application/json"
  //         }
  //     }).then((res) => {
  //         console.log(res)
  //         if(res.data.results[0].length!==0){
  //         axios.delete(`https://r5ctn9z9.lc-cn-n1-shared.com/1.1/classes/image/${res.data.results[0].objectId}`, {
  //             headers: {
  //                 " X-LC-Id": "r5CTN9z96pCW8mI8fx9YxOmw-gzGzoHsz",
  //                 "X-LC-Key": "8gSsl4Sz0ILMiQeMNMA8xQqg",
  //                 "Content-Type": "application/json"
  //             }
  //         }).then((res) => {
  //             // console.log(res)
  //             console.log('附属图片删除成功')
  //         }).catch((error) => {
  //             console.log(error)
  //         })
  //     }
  //     }).catch((error)=>{
  //         console.log(error)
  //     })







  //     axios.delete(`https://r5ctn9z9.lc-cn-n1-shared.com/1.1/classes/bscs/${objectId}`,{
  //         headers:{
  //             " X-LC-Id": "r5CTN9z96pCW8mI8fx9YxOmw-gzGzoHsz",
  //             "X-LC-Key": "8gSsl4Sz0ILMiQeMNMA8xQqg",
  //             "Content-Type": "application/json"
  //         }
  //     }).then((res)=>{
  //         console.log('删除成功')


  //         axios.get(`https://r5ctn9z9.lc-cn-n1-shared.com/1.1/classes/food?where={"Commodity_id":"${objectId}"}`, {
  //         headers: {
  //             " X-LC-Id": "r5CTN9z96pCW8mI8fx9YxOmw-gzGzoHsz",
  //             "X-LC-Key": "8gSsl4Sz0ILMiQeMNMA8xQqg",
  //             "Content-Type": ""
  //         }
  //     }).then((e) => {
  //         console.log(e)

  //         if(e.data.results.length!==0){
  //             axios.delete(`https://r5ctn9z9.lc-cn-n1-shared.com/1.1/classes/food/${e.data.results[0].objectId}`, {
  //             headers: {
  //                 " X-LC-Id": "r5CTN9z96pCW8mI8fx9YxOmw-gzGzoHsz",
  //                 "X-LC-Key": "8gSsl4Sz0ILMiQeMNMA8xQqg",
  //                 "Content-Type": ""
  //             }
  //         }).then(() => {
  //             console.log("删除成功")

  //             // navigate('/dianpu')
  //         }).catch((error)=>{
  //             console.log('出错',error)
  //         })
  //         }
  //         // navigate('/dianpu')


  //     })




  //     }).catch((error)=>{
  //         console.log('删除失败',error)
  //     })
  // }
  return (
    <div>
      <Input style={{ width: '300px' }} type='text' value={searchTerm} onChange={(e) => { setSearchTerm(e.target.value) }} />
      <Button onClick={handleSearch}>搜索</Button>
      <Table
        dataSource={datanew()}
        columns={columns}
        // dateFormat="yyyy-MM-dd"
        pagination={{
          current: currentPage,
          total: totalPages * 10,
          pageSize: 10,
          onChange: handlePageChange
        }}
      />

    </div>
  );
};

export default User2;